package servers;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import start.Merge;

import xchange.Debug;

public class StorageServerThread implements Runnable {

	Socket socket = null;
	PrintWriter out = null;
	BufferedReader in = null;
	Merge merge;
	String line;

	public StorageServerThread(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		try {

			System.out.println("Made connection");

			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

			while ((line = in.readLine()) != null) {
				System.out.println("Een bericht " + line);
				if (line.startsWith("POST")) {
					handlePost(line);
				}

				else if (line.startsWith("GET")) {
					handleGet(line);
				}

				else if (line.startsWith("REMOVE")) {
					handleRemove(line);
				}

				else {
					handleError();
				}
			}

			System.out.println("Close connection");

			out.close();
			in.close();
			socket.close();
		} catch (Exception e) {
			//e.printStackTrace();
		}
	}

	private void handlePost(String line) throws Exception {
		if (Debug.DEBUG) {
		    System.out.println("Storageserver received : " + line);
		}
		
		line = line.substring(5);
		
		System.out.println(line);
		
		File f=new File("myfile.txt");
		if(!f.exists()){
			f.createNewFile();
		}
		
		FileWriter fstream = new FileWriter("./files/" + line);
		BufferedWriter writer = new BufferedWriter(fstream);
		
		out.println("OK");
	
		if ((line = in.readLine()) != null) 
		{
			System.out.println("Response: " + line);
		}
    	
		System.out.println(line);
		
		writer.write(line);
		writer.close();
		
		//out.println("OK");
		if (Debug.DEBUG) {
		    System.out.println("Storageserver : added block to file");
		}
    }

	private void handleGet(String line) throws Exception {
		if (Debug.DEBUG) {
			System.out.println("Storageserver received : " + line);
		}

		line = line.substring(0, 3);
		
		String[] result = line.split(":");
		
		merge = new Merge(result[0], Integer.parseInt(result[1]));
		
		String lineToWrite = merge.merge();
		
		out.println(lineToWrite);
		
		if (Debug.DEBUG) {
			System.out.println("Storageserver : sent block from file");
		}
	}

	private void handleRemove(String line) throws Exception {
		if (Debug.DEBUG) {
			System.out.println("Storageserver received : " + line);
		}

		// this is a stub ! your code here

		out.println("OK");
		if (Debug.DEBUG) {
			System.out.println("Storageserver : all files removed !");
		}
	}

	private void handleError() throws Exception {
		out.println("FAIL");
	}

}
